/**
 *    Copyright 2009-2017 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.parsing;

/**
 * 【注释】通用标记解析器，处理的是SQL脚本中#{parameter}、${parameter}参数，
 * 根据给定TokenHandler（标记处理器）来进行处理，TokenHandler是标记真正的处理器。
 * GenericTokenParser解析器只是处理器处理的前提工序——解析，该类重在解析，而非处理，
 * 具体的处理会调用具体的TokenHandler的handleToken()方法来完成。
 * 
 * @author Clinton Begin
 */
public class GenericTokenParser {

	/**
	 * 开始标记符
	 */
	private final String openToken;
	/**
	 * 结束标记符
	 */
	private final String closeToken;
	/**
	 * 标记处理器
	 */
	private final TokenHandler handler;

	/**
	 * 带参数的构造器
	 * 
	 * @param openToken
	 * @param closeToken
	 * @param handler
	 */
	public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
		this.openToken = openToken;
		this.closeToken = closeToken;
		this.handler = handler;
	}

	/**
	 * 解析方法
	 * 
	 * @param text
	 * @return
	 */
	public String parse(String text) {
		if (text == null || text.isEmpty()) {
			return "";
		}
		// search open token
		int start = text.indexOf(openToken, 0);
		if (start == -1) {// 不存在开始标记，直接返回
			return text;
		}
		// 转换成字符数组
		char[] src = text.toCharArray();
		// 偏移量，即已经解析到的位置，默认从0开始
		int offset = 0;
		// 需要返回的字符串变量
		final StringBuilder builder = new StringBuilder();
		StringBuilder expression = null;
		while (start > -1) {// 如果可能存在开始标记
			// 存在开始标记，且开始标记前有转义字符，反斜杠"\",当有转义字符反斜杠时，默认该标记字符不做特殊处理
			// 即，不把该标记字符作为参数进行处理
			if (start > 0 && src[start - 1] == '\\') {
				// this open token is escaped. remove the backslash and continue.
				builder.append(src, offset, start - offset - 1).append(openToken);
				offset = start + openToken.length();
			} else {//存在开始标记，且需要特殊处理，即作为参数进行处理
				// found open token. let's search close token.
				if (expression == null) {
					expression = new StringBuilder();
				} else {
					expression.setLength(0);
				}
				builder.append(src, offset, start - offset);
				offset = start + openToken.length();
				int end = text.indexOf(closeToken, offset);
				while (end > -1) {//存在结束标记时
					if (end > offset && src[end - 1] == '\\') {//如果结束标记前面有转义字符时
						// this close token is escaped. remove the backslash and continue.
						expression.append(src, offset, end - offset - 1).append(closeToken);
						offset = end + closeToken.length();
						end = text.indexOf(closeToken, offset);
					} else {//不存在转义字符，即需要作为参数进行处理
						expression.append(src, offset, end - offset);
						offset = end + closeToken.length();
						break;
					}
				}
				if (end == -1) {
					// close token was not found.
					builder.append(src, start, src.length - start);
					offset = src.length;
				} else {
					//首先根据参数的key（即expression）进行参数处理，返回?作为占位符
					builder.append(handler.handleToken(expression.toString()));
					offset = end + closeToken.length();
				}
			}
			start = text.indexOf(openToken, offset);
		}
		if (offset < src.length) {
			builder.append(src, offset, src.length - offset);
		}
		return builder.toString();
	}
}
